package com.yz.sharkim.server;

import com.yz.sharkim.handler.DispatchRouterHandler;
import com.yz.sharkim.handler.RouterHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author yz
 */
@Slf4j
@Component
public class NettyServer implements ApplicationListener<ApplicationReadyEvent> {

    @Value("${shark.port}")
    private int port;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        DispatchRouterHandler.initRouter(event.getApplicationContext());

        val serverBootstrap = new ServerBootstrap();
        val parent = new NioEventLoopGroup();
        val child = new NioEventLoopGroup();
        try {
            serverBootstrap.group(parent, child)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            val pipeline = ch.pipeline();
                            pipeline.addLast(new HttpRequestDecoder());
                            pipeline.addLast(new HttpObjectAggregator(65535));
                            pipeline.addLast(new HttpResponseEncoder());
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                            pipeline.addLast(new RouterHandler());
                        }
                    });
            val future = serverBootstrap.bind(port).sync();
            log.info("Netty start success");
            future.channel().closeFuture().sync();
            log.info("Netty end");
        } catch (Exception e) {
            log.error("Netty error: {}", e.getMessage());
        } finally {
            parent.shutdownGracefully();
            child.shutdownGracefully();
        }
    }
}
